// pages/addMedicinePlan/addMedicinePlan.js
// 24 小时 Unix时间戳 86400000
var util = require('../utils');
Page({
  getStartTime(){
      var t = this.formatTime(new Date(), 'Y-M-D');
      console.log(t);
      //console.log(this.data.time);
      var time = t + " " + this.data.time;
      console.log(time);
      var repTime = time.replace(/-/g, '/');
      var timeTamp = Date.parse(repTime);
      return timeTamp;
  },

  formatNumber(n){
      n = n.toString()
      return n[1] ? n : '0' + n
  },
// navigateBack
  formatTime(number, format){
      var formateArr = ['Y', 'M', 'D'];
      var returnArr = [];
      var date = new Date(number);
      returnArr.push(date.getFullYear());
      returnArr.push(this.formatNumber(date.getMonth() + 1));
      returnArr.push(this.formatNumber(date.getDate()));
      for (var i in returnArr) {
          format = format.replace(formateArr[i], returnArr[i]);
      }
      return format;
  },

  updateValue(e) {
      let name = e.currentTarget.dataset.name;
      console.log(name);
      let nameMap = {}
      nameMap[name] = e.detail && e.detail.value
      this.setData(nameMap)
      console.log(e.detail.value)
    },


  /**
   * 页面的初始数据
   */
  data: {
      oriName:"",
      name: "",
      time: "",
      cycle: "",
      intro: "",
      num:"",
      startTime:"",
      endTime:"",
      array: ['1','2','3','4','5','6','7',8,9,10,11,12,13,14,21,28,35,60,90,120,150,180,360],
      // index: 0,
      list:[]
  },
  /**
   * 生命周期函数--监听页面加载 
   */
  onLoad: function (options) {
      this.getStartTime();
  },
  dateLater(dates, later) {
    let dateObj = {};
    let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
    let date = new Date(dates);
    date.setDate(date.getDate() + later);
    let day = date.getDay();
    dateObj.dates = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "月" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate()) + "日";
    dateObj.newdates = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
    dateObj.year = date.getFullYear();
    dateObj.month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
    dateObj.day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
    dateObj.week = show_day[day];
    return dateObj;
  },
  addMedicinePlan(){
      var that = this;
      const day = 86400;
      this.data.startTime = this.formatTime(new Date(), 'Y-M-D');
      var t = this.getStartTime();
      t /= 1000;
      var et = t + day * (this.data.cycle - 1);
      //var TimeList = util.getDates(this.data.cycle,this.data.startTime);
      this.data.endTime = util.getDates(this.data.cycle,this.data.startTime);
      //this.data.endTime = TimeList[-1].year+"-"+TimeList[-1].month+"-"+TimeList[-1].day;
      this.data.oriName = this.data.name;
      
      if(this.data.name=='') {
        wx.showToast({
            icon:"none",
            title: '药物名不能为空',
        })
      }
      else if(this.data.intro == '') {
          wx.showToast({
              icon:"none",
              title: '药物贴士不能为空',
            })
      }else if(this.data.cycle == '') {
        wx.showToast({
            icon:"none",
            title: '服药周期不能为空',
          })
      }else if(this.data.num == '') {
        wx.showToast({
            icon:"none",
            title: '用药剂量不能为空',
          })
      }else if(this.data.time == '') {
        wx.showToast({ 
            icon:"none",
            title: '服药时间不能为空',
        })
    }else {
      wx.cloud.database().collection('medicineRemind')
      .add({
          data:{
              name: this.data.name,
              intro: this.data.intro,
              time: this.data.time,              
              cycle: this.data.array[this.data.index],
              cycle: this.data.cycle,
              num: this.data.num,
              startTime: this.data.startTime,
              endTime: this.data.endTime
          }
      })
      .then(res=>{
          console.log('添加成功', res);
          wx.showToast({
            icon:"none",
            title: '添加成功',
          })
      }).catch(res=>{
          console.log('添加失败', res);
          wx.showToast({
            icon:"none",
            title: '添加失败',
          })
      })
    }

      wx.cloud.database().collection('medicineBox').get()
      .then(res => {
        var inMedicineBox = 1;
        console.log(res.data,"zzzz");
        for(let i = 0; i < res.data.length; i++) {
          console.log(res.data[i].name, this.data.oriName, "aaa");
          if(res.data[i].name == this.data.oriName) {
            inMedicineBox = 2;
            break;
          }
        }
        console.log(inMedicineBox, "wuwuw");
        if(inMedicineBox == 1) {
          console.log(this.data.oriName);
          wx.reLaunch({
            url: '/pages/addMedicinePlanBox/addMedicinePlanBox?name=' + this.data.oriName + "&&intro=" + this.data.intro,
          })
          .catch((error) => {
            console.error(error);
          })
        }
      })
      wx.addPhoneRepeatCalendar({
        title: "服用" + this.data.name + this.data.num,
        startTime: t,
        endTime: et,
        repeatInterval: "day",
        description: this.data.intro,
    }).catch((error) => {
      console.error(error);
    });

    wx.reLaunch({
      url: '../main/main',
    })
  },

    addToMedicineBox(){
      wx.navigateTo({
        url: '/pages/addMedicinePlan/addMedicinePlan?name=' + this.data.oriName + "&&intro=" + this.data.intro,
      })
    },

    picToTxt() {
        const that = this
        wx.chooseImage({
          success: (res) => {
            //获取图片的临时路径
            const tempFilePath = res.tempFilePaths[0]
            //根据官方的要求  用base64字符编码获取图片的内容
            wx.getFileSystemManager().readFile({
              filePath: tempFilePath,
              encoding: 'base64',
              success: function (res) {
                //调用方法
                that.getImgInfo(res.data)
              },
            })
          },
        })
      },
      //根据图片的内容调用API获取图片文字
      getImgInfo: function (imageData) {
        wx.showLoading({
          title: '识别中...',
        })
        var that = this
        that.getBaiduToken().then(res => {
          console.log(res)
          //获取token
          const token = res.data.access_token
          console.log(token)
          const detectUrl = `https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=${token}` // baiduToken是已经获取的access_Token      
          wx.request({
            url: detectUrl,
            data: {
              image: imageData
            },
            method: 'POST',
            dataType: 'json',
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 必须的        
            },
            success: function (res, resolve) {
                console.log(res)
                //将 res.data.words_result数组中的内容加入到words中           
                that.setData({
                  words: res.data.words_result
                })
                console.log(res.data.words_result, "你好");
                var wordss = res.data.words_result;
                console.log(wordss, "zzh");
                var na='';
                var intro ='';
                var time = 10;
                var num="";
                var f = 1;
                var cycle = '';
                for(let i = 0; i < wordss.length; i++) {
                    console.log(wordss[i].words);
                    if(wordss[i].words.substring(0, 4) === "药物名称") {
                        na = wordss[i].words.substring(4, wordss[i].words.length);
                    }else if(wordss[i].words.substring(0, 4) === "注意事项") {
                        intro  = wordss[i].words.substring(4, wordss[i].words.length);
                    }else if(wordss[i].words.substring(0, 4) === "服用周期") {
                        cycle =  wordss[i].words.substring(4, wordss[i].words.length - 1);
                    }else if(wordss[i].words.substring(0, 4) === "服用剂量") {
                        num = wordss[i].words.substring(4, wordss[i].words.length);
                    }
                    wx.hideLoading()
                }
                that.setData({
                    name: na,
                    intro: intro,
                    cycle: cycle,
                    num: num,
                    time: time,                    
                })
              // 提取药物和简介
            },
            fail: function (res, reject) {
              console.log('get word fail：', res.data);
              wx.hideLoading()
            },
            complete: function () {
              wx.hideLoading()
            }
          })
        })
      },
      // 获取百度access_token  
      getBaiduToken: function () {
        return new Promise(resolve => {
          var APIKEY = "HgxRmg952flZtoR7E2CidFls"
          var SECKEY = "b3kGY6r5BBtw6YldnpFyojx32VxNhsWn"
          var tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${APIKEY}&client_secret=${SECKEY}`
          var that = this;
          wx.request({
            url: tokenUrl,
            method: 'POST',
            dataType: 'json',
            header: {
              'content-type': 'application/json; charset-UTF-8'
            },
            success: function (res) {
              console.log("[BaiduToken获取成功]", res);
              return resolve(res)
            },
            fail: function (res) {
              console.log("[BaiduToken获取失败]", res);
              return resolve(res)
            }
          })
        }).catch((error) => {
          console.error(error);
        })
      },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    navigateBack: function () {  
      wx.navigateBack({ changed: true });//返回上一页  
  },
  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
    this.data.cycle=this.data.array[this.data.index]
    //this.data.cycle.input
  }
  // data: {
  //   array: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,21,28,35,60,90,120,150,180,360],

  //   index: 0,
  // }
})